package com.zofer.study.thread.abc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description 多线程打印ABC
 * 使用 ReentranLick And Condition 打印ABC
 * @date: 2020/10/15 15:07
 */
public class ABCPrintByCondition {

    private static ReentrantLock lock = new ReentrantLock();

    private static Condition aCondition = lock.newCondition();
    private static Condition bCondition = lock.newCondition();
    private static Condition cCondition = lock.newCondition();
    private static String currentThreadName = "A";

    static class ATask implements Runnable{
        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (!"A".equals(currentThreadName)){
                        //等待唤醒,释放锁
                        aCondition.await();
                    }
                    System.out.print("A");
                    currentThreadName = "B";
                    bCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }


    static class BTask implements Runnable{
        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (!"B".equals(currentThreadName)){
                        //等待唤醒,释放锁
                        bCondition.await();
                    }
                    System.out.print("B");
                    currentThreadName = "C";
                    cCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }


    static class CTask implements Runnable{
        public void run() {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (!"C".equals(currentThreadName)){
                        //等待唤醒,释放锁
                        cCondition.await();
                    }
                    System.out.print("C");
                    currentThreadName = "A";
                    aCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new ATask()).start();
        new Thread(new BTask()).start();
        new Thread(new CTask()).start();
    }
}
